package com.liqy.api.controller;
/**
 * Created by
 *
 * @auth: liqy
 * on 2021/12/17 17:07.
 * desc:
 */

import com.liqy.api.domain.CodeMsg;
import com.liqy.api.domain.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName: GlobalExceptionHandler
 * @Description: 全局异常处理
 * @Author: liqy
 * @CreateDate: 2021/12/17 17:07
 * @UpdateUser: liqy
 * @UpdateDate: 2021/12/17  17:07
 * @UpdateRemark: update TODO
 * @Version: 1.0
 */
@ControllerAdvice //该注解定义全局异常处理类
//@ControllerAdvice(basePackages ="com.example.demo.controller") 可指定包
@ResponseBody
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value=Exception.class) //该注解声明异常处理方法
    public Response<String> exceptionHandler(HttpServletRequest request, Exception e){
        log.debug("request:{} occure an exception: cause:{}, message:{}", request.getPathInfo(), e.getCause(), e.getMessage());
        if(e instanceof BindException) {
            BindException ex = (BindException)e;
            List<ObjectError> errors = ex.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return Response.errResponse(CodeMsg.BIND_ERROR.fillArgs(msg).getMsg());
        } else {
            return Response.errResponse(CodeMsg.SERVER_ERROR.fillArgs(e.getLocalizedMessage()).getMsg());
        }
    }
}
